var express = require('express');

var multer  = require('multer');
var upload = multer({dest: 'upload_tmp/'},{ storage: storage });

var app = express();
var fs = require("fs");
var path = require('path');
//创建目录
var createFolder = function(folder){
  try{
      fs.accessSync(folder); 
  }catch(e){
      fs.mkdirSync(folder);
  }  
};
var uploadFolder = './upload_tmp/';
//createFolder(uploadFolder);
// 通过 filename 属性定制
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
      cb(null, uploadFolder);    // 保存的路径，备注：需要自己创建
  },
  filename: function (req, file, cb) {
      // 将保存文件名设置为 字段名 + 时间戳，比如 logo-1478521468943
      cb(null, file.fieldname + '-' + Date.now());  
  }
});
// 日期方法.
function getDate() {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    return year + '-' + month + '-' + day
}
// 单图上传
app.post('/uploadImg', upload.single('content'), function(req, res, next){
 //res.setHeader('Content-Type', 'multipart/form-data');
 createFolder(uploadFolder+path.parse(req.file.originalname).ext.substring(1,path.parse(req.file.originalname).ext.length)+'/');
  //获取详细信息
  var file = req.file;//From the name
  console.log('原始文件名：%s',req.file.originalname);
  console.log('文件类型：%s', path.parse(req.file.originalname).ext);
  
  console.log('文件大小：%s', file.size);
  console.log('文件保存路径：%s', file.path);

  // 时间戳
  let timestamps = Math.round(new Date().getTime() / 1000).toString();
  let fileNameArr=req.file.originalname.split(".");
  let oldPath=file.path;
  let newPath=uploadFolder+path.parse(req.file.originalname).ext.substring(1,path.parse(req.file.originalname).ext.length)+'/'+fileNameArr[0]+'_'+getDate()+'_'+timestamps+path.parse(req.file.originalname).ext;
  fs.rename(oldPath, newPath, function (err) {
      if(err)
      {
        var result = {
            status: 0,
            message: "上传失败",
            data: err
         }
        res.jsonp(result);
      }else
      {
          var result = {
            status: 1,
            message: "上传成功",
            data: fileNameArr[0]
            }
        res.jsonp(result);
      }      
  })    
});

app.get('/form', function(req, res, next){
    var form = fs.readFileSync('./public/index.html', {encoding: 'utf8'});
    res.send(form);
});   

var server = app.listen(8081, function () {

  var host = server.address().address
  var port = server.address().port
  console.log("应用实例，访问地址为 http://%s:%s", host, port)

})